import React , {Component} from 'react';
import Config from '../helper/config';
import FullScreen from '../component/FullScreen';
import Modal from '../component/Modal';
import Toast from '@welab/xlib-react-components/components/Toast';
import { livenessLimit } from '../liveness/constants';
import { createObjectURL, revokeObjectURL } from '../liveness/compatible';
import {Steps, Step} from '../component/StepIndex'

class FaceCert extends Component{
  constructor(props){
    super(props);
    this.state = {
      faceUrl: '//web.wolaidai.com/img/jddv3/scan.png',
      loadDesc: '正在上传...',
      showModal: false
    }
  }

  componentDidMount() {
    utils.updatePageTitle("刷脸认证");
  }

  uploadVideo(event) {
    const check = function(file) {
      const promise = new Promise((resolve, reject) => {
        // debugger;
        if (file.size > livenessLimit.size) {
          reject({ errMsg: '视频大小大于15M，请重新上传！' });
          return;
        }

        const video = document.createElement('video');
        let metadataloaded = false;
        video.preload = 'metadata';
        video.onloadedmetadata = () => {
          metadataloaded = true;
          revokeObjectURL(video.src);
          if (video.duration > livenessLimit.duration) {
            reject({ errMsg: '视频时间大于5s，请重新上传！' });
          } else {
            resolve({ file });
          }
        };
        video.src = createObjectURL(file);
        setTimeout(() => {
          if (!metadataloaded) {
            resolve({ file });
          }
        }, 2000);
      });
      return promise;
    };

    const file = event.target.files[0];
    check(file).then(() => {
      this.setState({
        showModal: true
      })
      const handleRes = (res) => {
        this.setState({
          loadDesc: res.livenessPassed ? '刷脸成功' : '刷脸失败，请重新尝试。'
        },() => {
          setTimeout(() => {
            this.setState({
              showModal: false
            },() => {
              this.setState({
                loadDesc: '正在上传...'
              })
            })
            res.livenessPassed && this.props.history.push('submitApply');
          },1000)
        })
      }
      const params = {
        platformPath: 'welab-ocr',
        videoFile: file
      }
      API.upload('v3/liveness/liveness_video', params).done(data => {
        this.setState({
          loadDesc: '正在识别...'
        })
        API.post('v3/liveness/liveness',{ platformPath:'welab-ocr' }).done( data => {
          const res = data.data;
          handleRes(res);
        }).fail(xhr => {
          handleRes({ livenessPassed: false });
          utils.errorHandle(xhr, '',this.toast.show);
        });
      }).fail((xhr) => {
        handleRes({ livenessPassed: false });
        utils.errorHandle(xhr, '',this.toast.show);
      });
    },(err) => {
      console.log(err);
      this.toast.show(err.errMsg);
    })
    
  }

  render(){
    const { faceUrl, showModal,loadDesc } = this.state;
    return(
      <FullScreen color='#fff' className='face-cert' footer={false}>
        <Steps current={1}>
          <Step title="身份信息" icon={<i className="iconfont proIcon">&#xe65b;</i>} />
          <Step title="实名认证" icon={<i className="iconfont proIcon" >&#xe65c;</i>} />
          <Step title="提交申请" icon={<i className="iconfont proIcon" >&#xe65a;</i>} />
        </Steps>
        <div className='face-div'>
          <p>您的借款申请即将提交，为防止资金被他人盗用</p>
          <p>请按下面提示刷脸，确认是本人操作</p>
          <img className='camera-face' src={ faceUrl }/>
          <img className='eyes' src=""/>
          <p className='f-desc'>录制自拍视频，不超过<span>5</span>秒</p>
          <p className='f-desc'>拍摄时请眨眼<span>2-3</span>次</p>
        </div>
        <button className='btn' onClick={ () => this.vedioInput.click() }>开始刷脸</button>
        <p className='face-msg'> 已成功保护<span>5,527,534+</span>账号安全</p>
        <input ref={ input => this.vedioInput = input } className='video' type='file' accept='video/*' capture='true' onChange={ this.uploadVideo.bind(this) }/>
        <Toast timeout={1500} ref={ toast => this.toast = toast }></Toast>
        <Modal show={ showModal }>
          <div className='face-modal'>
            <img className='person' src="//web.wolaidai.com/img/jddv3/scan.png"/>
            <img className='eyes' src=""/>
            <div className='top'></div>
            <div className='over'></div>
            <div className='bottom'>
              <p className='desc'>{ loadDesc }</p>
            </div>

          </div>
        </Modal>
      </FullScreen>
    )
  }
}
export default FaceCert;